#pragma once
#include "Log.hpp"
#include "uncopyable.hpp"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include "Inet.hpp"
#include <string>
#include <functional>
#include "Route.hpp"

// UDP_echo_Server 的服务端：接受并显示客户端发送的信息，最终把信息发回客户端
using namespace log_ddsm;
enum
{
    default_sockfd = -1,
    default_localport = -1,
    socket_err = 1,
    bind_err = 3,
    SIZE = 2048
};

class UdpServer : public uncopyable // 服务器一般无法拷贝，赋值
{
public:
    UdpServer(Route::service_t func,uint16_t localport = default_localport)
        : _sockfd(default_sockfd), _localport(localport), _isrunning(false),_func(func)
    {
    }
    void Init() // 创建套接字并绑定
    {
        // 创建一个udp的网络套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket creat fail!\n");
            exit(socket_err);
        }
        LOG(DEBUG, "socket creat success | socket = %d\n", _sockfd);

        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));

        // 填写本地的ip地址和端口号
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport);
        // local.sin_addr.s_addr = inet_addr(_localip.c_str());
        local.sin_addr.s_addr = INADDR_ANY;

        // 绑定socket和ip 端口号
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind fail!\n");
            exit(bind_err);
        }
        LOG(DEBUG, "socket bind success\n");
    }
    void Start() // 不断收发信息
    {
        _isrunning = true;
        char message[SIZE] = {0};
        while (1)
        {
            // do service
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            // len，输出型参数，表明peer字段的长度
            ssize_t n = recvfrom(_sockfd, message, sizeof(message) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                // 将网络序列转化为主机序列
                Inet inet(peer);
                // 读取成功
                message[n] = '\0';
                std::cout << "[" << inet.IP() << " " << inet.PORT() << "] :" << message << std::endl;
                
                //回调上层的函数
                _func(_sockfd,message,inet);
            }
        }
    }
    ~UdpServer()
    {
        if (_sockfd > default_sockfd)
        {
            close(_sockfd);
        }
    }

private:
    int _sockfd;         // 网络套接字，类似于一个文件fd
    uint16_t _localport; // 本进程的端口号

    bool _isrunning; // 服务器是否正在运行

    Route::service_t _func;//上层的回调函数
};